package models

import (
	"github.com/jinzhu/gorm"
	"kop/modules/ranking/entity"
)

func AutoMigrate(dB *gorm.DB) {

	dB.AutoMigrate(new(entity.King))
	dB.AutoMigrate(new(entity.Popularity))
}

func GetKings(dB *gorm.DB, serverID int32) []entity.King {

	var data []entity.King
	if err := dB.Where("server_id = ?", serverID).Find(&data).Error; err != nil {
		panic(err)
	}

	return data
}

func GetKing(dB *gorm.DB, itemID, serverID int32) (entity.King, bool) {

	var data = entity.King{ItemID: itemID, ServerID: serverID}
	if err := dB.First(&data).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return data, false
		} else {
			panic(err)
		}
	}

	return data, true
}

func CreateKing(dB *gorm.DB, itemID, serverID, roleID int32) entity.King {

	var data = entity.King{
		ItemID:   itemID,
		ServerID: serverID,
		RoleID:   roleID,
	}

	if err := dB.Create(&data).Error; err != nil {
		panic(err)
	}

	return data
}

func SaveKing(dB *gorm.DB, data *entity.King) {

	if err := dB.Save(&data).Error; err != nil {
		panic(err)
	}
}
